import { Component, OnInit } from '@angular/core';
import { JsonApiService } from "app/core/api/json-api.service"; //http请求配置引入
import { Router, ActivatedRoute } from "@angular/router"; //路由引入
import { config } from '../../shared/smartadmin.config';

declare var $: any;
declare var echarts:any;
@Component({
	selector: 'sa-user',
	templateUrl: './user.component.html',
	styleUrls:['./user.css']
})
export class UserComponent implements OnInit {
	startTime:string = '';//table时间控件
	endTime:string = '';//table时间控件
	userName:string = ''; //用户ID
	userId:string = ''; //用户名称
	userList=[];
	// specifyId = {
		
	// }

	specifyId = {
		picker1:'datetimepicker3',
		picker2:'datetimepicker4'
	};
	specifyTime = {
		startTime:'',
		endTime:'',
	};

	interfaceName='';
	interfaceKey='';

	echartX = [];
	echartY = [];
	
	interfaceList = [];	//右侧接口select2的数据

	tableList = [];		//表格信息

	indNumber = null;
	warnPeak:any = '';		//配额

	layerSpecifyTime = {		//弹出层默认时间
		'startTime':'',
		'endTime':''
	}
	layerSpecifyStartTime = '';	
	layerSpecifyEndTime = '';
	activeIndex = 0;

	tableActive = {		//当前选中的一列数据
		"createTime": "",
		"endTime": "",
		"id": "",
		"interfaceKey": "",
		"interfaceName": "",
		"reqCount": "",
		"startTime": "",
		"updateTime": "",
		"userId": "",
		"userName": "",
	}
	constructor(private jsonApiService: JsonApiService, private router: Router, private activatedRoute: ActivatedRoute ) {
		activatedRoute.queryParams.subscribe(queryParams => {
			
		});
	}

	//时间change回调
	getSelectTableTime(val){
		this.startTime = val.startTime;
		this.endTime = val.endTime;
		if(!this.startTime || !this.endTime){
			this.jsonApiService.message('请选择时间');
			return false;
		}
		// 等待页面默认数据返回就发送请求
		this.initAllUser().then(()=>{
			this.selectUserName();
			this.table_search();
		});
	} 

	ngOnInit(){
		// this.initAllUser().then(()=>{
		// 	this.selectUserName();
		// 	this.table_search();
		// });
		this.select2Data();
	}

	//擦除用户所选值
	delUserName(){
		this.userName = '';
		this.userId = '';
		//采用简单粗暴的方法清除;官方推荐的方法失效
		var str=$("<span class='select2-selection__placeholder'>请选择</span>");
		$('#userNameSelect2').val("");
		$("#select2-userNameSelect2-container").empty();
		$("#select2-userNameSelect2-container").attr("title","");
		$("#select2-userNameSelect2-container").prepend(str);
		this.userId = '';

		this.table_search();

	}

	//擦除接口所选值
	delUserName1(){
		this.userName = '';
		//采用简单粗暴的方法清除;官方推荐的方法失效
		var str=$("<span class='select2-selection__placeholder'>请选择</span>");
		$('#userNameSelect1').val("");
		$("#select2-userNameSelect1-container").empty();
		$("#select2-userNameSelect1-container").attr("title","");
		$("#select2-userNameSelect1-container").prepend(str);

		this.interfaceKey = '';
		this.interfaceName = '';
		this.table_search();

	}

	//初始化select2 选项
	selectUserName(){
		var that = this;
		System.import('script-loader!select2/dist/js/select2.min.js').then(()=>{
			System.import('assets/js/select2-zh-CN.js').then(()=>{
				$("#userNameSelect2").select2({
			    	language : "zh-CN",
			    	placeholder :"请选择",
			    	allowClear : true,
			    	data : this.userList,//为Select添加数据
			        templateResult: this.formatRepo
			    }).on ("select2:select", function (e){
		        	  	var data = e.params.data;
		        	  	that.userName = data.text;
						  that.userId = data.id;
						  that.table_search();

				});
				

				$("#userNameSelect1").select2({
			    	language : "zh-CN",
			    	placeholder :"请选择接口名",
			    	allowClear : true,
			    	data : this.interfaceList,//为Select添加数据
			        templateResult: this.formatRepo
			    }).on ("select2:select", function (e){
						var data = e.params.data;
		        	  	that.interfaceName = data.text;
						  that.interfaceKey = data.id;
						  
						  that.table_search();
		        });

			});
		})
	}
	//select2 格式回调函数
	formatRepo (state) {
		if (!state.id) {return state.text};
		var $state = $('<span><i class="fa fa-user green"></i>&nbsp;&nbsp;' + state.text + '</span>');
		return $state;
	}
	//拉取
	initAllUser(){
		var that = this;
		return new Promise(function (resolve, reject) {
			that.jsonApiService.http("user/getUserList.html",null).subscribe(data=> {
				if(data.success){
					var userList = data.data;
		        	var selectdata = [];
		        	for(var i = 0 ; i < userList.length ; i++) {
		        		var obj = {
		        			id:userList[i].id,
		        			text:userList[i].userName,
		        		}
		        		selectdata[i] = obj;
		        	}
				}
				that.userList = selectdata;
				resolve();
			})
		})
	}

	// 查询表格数据
	table_search(){
		if(!this.startTime || !this.endTime){
			this.jsonApiService.message('请选择时间');
			return false;
		}
		let reqdata = {
			'userId':this.userId,
			'interfaceKey':this.interfaceKey,
			'searchKey':'',
			'startTime':this.startTime,
			'endTime':this.endTime,
			'type':1
		}
		this.jsonApiService.http_obj('apiMonitoring/queryUserUsedApiCountList.html', reqdata).subscribe(result => {
			this.tableList = result.data;
			this.warnPeak = result.warnPeak;
		});
	}

	// 拉去右侧select2数据
	select2Data(){
		let reqdata = {
			'userId':this.userId,
			'interfaceKey':'',
			'searchKey':'',
			'startTime':this.startTime,
			'endTime':this.endTime,
		}
		this.jsonApiService.http_obj('apiConfig/getAllApiList.html ', reqdata).subscribe(result => {
			const self = this;
			result.data.forEach(item=>{
				self.interfaceList.push({
					'id':item.interfaceKey,
					'text':item.interfaceName
				});
			});
		});
	}

	showChart(val,item,index){
		this.tableActive = item;
		this.indNumber = index;
		let newTime = {
			'startTime':item.startTime,
			'endTime':item.endTime
		}
		this.layerSpecifyTime = newTime;
		val.show();
		// 今天到昨天赋值
		// const now = new Date();
		// let today = common.getTimeMmss(now);
		// let spaceTime = common.mmsstoTimestamp(today) - (60*60*24*1000);
		// const yesterday = new Date(spaceTime);
		// let yesterdayTime = common.getTimeMmss(yesterday);
		
		// let timeValue = {
		// 	'startTime':yesterdayTime,
		// 	'endTime':today
		// }
		// this.layerSpecifyTime = timeValue;
		// this.layerSpecifyStartTime = yesterdayTime;
		// this.layerSpecifyEndTime = today;
		this.getLayerTime(newTime);	//触发时间选择
		
		let reqdata = {
			'userId':item.userId,
			'interfaceKey':item.interfaceKey,
			// 'searchKey':this.searchKey,
			'startTime':item.startTime,
			'endTime':item.endTime,
			'type':1
		}
		this.jsonApiService.http_obj('apiMonitoring/queryUserUsedApiCountList.html', reqdata).subscribe(result => {
			// if(result.code == 0){
				this.echartX = [];
				this.echartY = [];
				result.data.forEach(item=>{
					this.echartX.unshift(item.startTime);
					this.echartY.unshift(item.reqCount);
				});
				this.echartsInit();
			// }
		});
	}

	cancelDeal(val){
		val.hide();
	}

	getLayerTime(val){
		this.layerSpecifyStartTime = val.startTime;
		this.layerSpecifyEndTime = val.endTime;
	}

	loadChart(){
		if(!this.layerSpecifyStartTime || !this.layerSpecifyEndTime){
			this.jsonApiService.message('请选择时间');
			return false;
		}
		let reqdata = {
			'userId':this.tableActive.userId,
			'interfaceKey':this.tableActive.interfaceKey,
			// 'searchKey':this.searchKey,
			'startTime':this.layerSpecifyStartTime,
			'endTime':this.layerSpecifyEndTime,
			'type':1
		}
		this.jsonApiService.http_obj('apiMonitoring/queryUserUsedApiCountList.html', reqdata).subscribe(result => {
			// if(result.code == 0){
				this.echartX = [];
				this.echartY = [];
				result.data.forEach(item=>{
					this.echartX.unshift(item.startTime);
					this.echartY.unshift(item.reqCount);
				});
				this.echartsInit();
			// }
		});
	}

	monthChart(){
		this.activeIndex == 1;
		const now = new Date();
		let nowTime = common.getTimeMmss(now);
		let spaceTime = common.mmsstoTimestamp(nowTime) - 30*(60*60*24*1000);
		const weak = new Date(spaceTime);
		let weakTime = common.getTimeMmss(weak);
		
		let newTime = {
			'startTime':weakTime,
			'endTime':nowTime,
		}
		this.layerSpecifyTime = newTime;

		this.layerSpecifyStartTime = weakTime;
		this.layerSpecifyEndTime = nowTime;

		this.loadChart();
	}

	weekChart(){
		this.activeIndex == 2;
		const now = new Date();
		let nowTime = common.getTimeMmss(now);
		let spaceTime = common.mmsstoTimestamp(nowTime) - 7*(60*60*24*1000);
		const weak = new Date(spaceTime);
		let weakTime = common.getTimeMmss(weak);
		
		let newTime = {
			'startTime':weakTime,
			'endTime':nowTime,
		}
		this.layerSpecifyTime = newTime;

		this.layerSpecifyStartTime = weakTime;
		this.layerSpecifyEndTime = nowTime;

		this.loadChart();
	}

	echartsInit(){
		const self = this;
		var myChart = echarts.init(document.getElementById('box'));

        // 指定图表的配置项和数据
        myChart.setOption({
			tooltip: {
				trigger: 'axis',
				axisPointer: {
					type: 'cross'
				},
			},
			xAxis: {
				type: 'category',
				splitLine: {show: false},
				data: self.echartX,
				name:'时间'
			},
			yAxis: {
				type: 'value',
				name:'并发次数'
			},
			series: [
				{
					data: self.echartY,
					type: 'line',
					smooth: false,
					areaStyle: {
						color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
							offset: 0,
							color: '#c23531'
						}, {
							offset: 1,
							color: '#ffe'
						}])
					},
					markLine: {
						silent: true,
						data: [
							{
								yAxis: self.warnPeak,
								lineStyle:{
									type:'solid'
								}
							}	
						],
						label:{
							position:'end',
							formatter:` 配额 \n${self.warnPeak}`
						},
						lineStyle:{
							color:'red'
						}
					}
				}
			],
			dataZoom:[
				{
					id: 'dataZoomX',
					type: 'slider',
					xAxisIndex: [0],
					filterMode: 'filter',
					start:0,
					end:100
				}
			]
		});	
	}
}